import { Request, Response } from 'express';
import CaptchaUtil from '@/utils/captcha.util';
import ApiResponse from '@/utils/api/api-response.util';
import rateLimit from 'express-rate-limit';
import { getLogger } from '@/utils/logger';

// 创建模块专用的日志记录器
const consoleLogger = getLogger("captcha-controller");
const logger = getLogger("captcha-controller", {
	console: false,
});

// 验证码请求频率限制
export const captchaLimiter = rateLimit({
  windowMs: 60 * 1000, // 1分钟窗口期
  max: 20, // 每个IP每分钟最多请求20次验证码（修改为更大的值）
  message: { code: 429, msg: '请求过于频繁，请稍后再试', data: null },
  standardHeaders: true,
  legacyHeaders: false,
});

class CaptchaController {
  /**
   * 获取验证码
   * @param req 请求对象
   * @param res 响应对象
   */
  async getCaptcha(req: Request, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("获取验证码请求", {
        ip: req.ip,
        operator: req.user?.userName || 'anonymous',
      });
      
      // 生成验证码
      const captcha = await CaptchaUtil.generate();
      
      // 结果日志
      logger.info("获取验证码成功", {
        response: {
          uuid: captcha.uuid,
        },
        operator: req.user?.userName || 'anonymous',
      });
      
      // 返回验证码图片和UUID
      ApiResponse.successWithoutWrapper(res, {
				uuid: captcha.uuid,
				img: captcha.img,
			});
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取验证码失败: ${error instanceof Error ? error.message : String(error)}`, {
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取验证码失败', 500);
      }
    }
  }
}

export default new CaptchaController(); 